package com.yuyu.shop.infrastructure.general.mq.ons;

import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.aliyun.openservices.ons.api.bean.ConsumerBean;
import com.aliyun.openservices.ons.api.bean.Subscription;
import com.yuyu.commons.constant.AliMqPropertiesConstant;
import com.yuyu.shop.infrastructure.general.mq.listener.OnsDelayBackOrderListener;
import com.yuyu.shop.infrastructure.general.mq.listener.OnsOrderListener;
import com.yuyu.shop.infrastructure.general.mq.listener.OnsSecKillListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;


/**
 * 定于消费者订阅以及绑定listener
 */
@Configuration
public class ONSConsumer {
   //监听器
    @Resource
    private OnsOrderListener onsOrderListener;

    @Resource
    private OnsSecKillListener onsSecKillListener;

    @Resource
    private OnsDelayBackOrderListener onsDelayBackOrderListener;

   @Bean(initMethod = "start",destroyMethod = "shutdown")
   //bean注解:start创建对象时会自动调用此类中的start方法初始化consumer(里面会用properties初始化consumer) destroyMethod销毁时会自动调用shutdown方法关闭连接
   public ConsumerBean createConsumerBean(){
       //创建一个properties以及consumerBean对象 基本配置
       Properties properties=new Properties();
       properties.put(PropertyKeyConst.NAMESRV_ADDR, AliMqPropertiesConstant.nameSrvAddress);
       //设置消费线程
       properties.put(PropertyKeyConst.ConsumeThreadNums,AliMqPropertiesConstant.threadNum);
       properties.put(PropertyKeyConst.GROUP_ID,AliMqPropertiesConstant.groupId);
       properties.put(PropertyKeyConst.SecretKey,AliMqPropertiesConstant.secretKey);
       properties.put(PropertyKeyConst.AccessKey,"1dasdas11515");
       ConsumerBean consumerBean = new ConsumerBean();
       consumerBean.setProperties(properties);
       //订阅关系
       Map<Subscription, MessageListener> subscriptionTable =new HashMap<>();
       subscriptionTable.put(getSubscription(AliMqPropertiesConstant.orderTopic,AliMqPropertiesConstant.OrderTag),onsOrderListener);
       subscriptionTable.put(getSubscription(AliMqPropertiesConstant.secKillOrderTopic,AliMqPropertiesConstant.secKillTag),onsSecKillListener);
       subscriptionTable.put(getSubscription(AliMqPropertiesConstant.delayOrderTopic,AliMqPropertiesConstant.sKillOrderTag),onsDelayBackOrderListener);
       consumerBean.setSubscriptionTable(subscriptionTable);
       return consumerBean;
   }

   private Subscription getSubscription(String topic,String tag){
       Subscription subscription = new Subscription();
       subscription.setTopic(topic);
       subscription.setExpression(tag);
       return subscription;
   }
}
